﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.Forum.Controls
{
    public class ForumsPostsViewControl : UserControl
    {
        protected HtmlAnchor _categoryLink;
        protected HtmlAnchor _forumLink;
        protected HtmlAnchor _topicLink;
        //protected HtmlAnchor _replyLink;

        protected Label _titleLabel;
        protected Repeater _messagesRepeater;

        protected HtmlAnchor _replyLink;
        protected HtmlAnchor _newLink;
        protected HtmlAnchor _replyBottomLink;
        protected HtmlAnchor _newBottomLink;

        protected HtmlGenericControl pagerPrevContainer;
        protected HtmlGenericControl pagerNextContainer;
        protected HtmlAnchor pagerPrevLink;
        protected HtmlAnchor pagerNextLink;

        private ForumRepository _forumRepository;
        private ForumRepository ForumRepository
        {
            get
            {
                if (_forumRepository != null)
                    return _forumRepository;

                _forumRepository = new ForumRepository(SPContext.Current.Web);
                return _forumRepository;
            }
        }

        protected override void OnInit(System.EventArgs e)
        {
            base.OnInit(e);            
            _messagesRepeater.ItemDataBound += MessagesRepeaterItemDataBound;
        }

        protected void MessagesRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            /*var c = e.Item.FindControl("messageActionsContainer");
            if (c != null)
                c.Visible = false;
            */
            var anchor = (HtmlAnchor) e.Item.FindControl("_commentsStartAnchor");
            if (e.Item.ItemIndex == 1)
            {
                anchor.Name = "comments";
            }
            else
                anchor.Visible = false;

            var editLink = (HtmlAnchor) e.Item.FindControl("editLink");
            editLink.Visible = false;
            var editSeparator = (Label) e.Item.FindControl("editSeparator");
            editSeparator.Visible = false;
            var explanationRow = (HtmlTableRow) e.Item.FindControl("_explanationRow");
            
            var post = (ForumPostDto) e.Item.DataItem;

            explanationRow.Visible = (post.Created != post.Modified);


            var user = SPContext.Current.Web.CurrentUser;
            if(user != null)
            {
                editLink.HRef = "/foorum/Lehed/default.aspx?control=UpdateMessage&topic={0}&post={1}&postmethod=Edit";
                editLink.HRef = string.Format(editLink.HRef, post.TopicId, post.Id);
                editLink.Visible = (user.LoginName == post.AuthorUserName || user.IsSiteAdmin);
                editLink.Attributes["class"] = GetPostClass(post, "you", "");
                editSeparator.Visible = editLink.Visible;
                editSeparator.Style["display"] = "inline";
            }

            var editorNameLabel = (Label) e.Item.FindControl("_editorNameField");
            editorNameLabel.Style["display"] = "inline";
            editorNameLabel.Text = post.ModifiedBy;
            if (!string.IsNullOrEmpty(post.EditorExplanation))
                editorNameLabel.Text += ":";
        }

        public object DataSource { get; set; }

        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            int id;
            if(!int.TryParse(Request.QueryString["topic"], out id))
            {
                //TODO: veateade
                return;
            }

            if (!string.IsNullOrEmpty(Request.QueryString["rss"]))
            {
                Response.Clear();
                Response.ContentType = "application/rss+xml";
                Response.Write(ForumRepository.GetTopicCommentsRss(id));
                Response.End();
                return;
            }

            var topic = ForumRepository.GetForumTopicById(id);
            var forum = ForumRepository.GetForumById(topic.ForumId);
            var category = forum.Category;

            Page.Title = Resources.Forum.ForumTitle + " > " + forum.Title + " > " + topic.Title + " | " + EnetaApplication.PortalTitle;

            _topicLink.HRef = string.Format(_topicLink.HRef, topic.Id);
            _topicLink.InnerText = topic.Title;

            //_replyLink.Visible = false;
            if (SPContext.Current.Web.CurrentUser != null)
            {
                //_replyLink.Visible = true;
                //_replyLink.HRef = string.Format(_replyLink.HRef, topic.Id);
            }

            _forumLink.HRef = string.Format(_forumLink.HRef, forum.Id);
            _forumLink.InnerText = forum.Title;

            _categoryLink.HRef = string.Format(_categoryLink.HRef, category.Id);
            _categoryLink.InnerText = category.Title;

            _titleLabel.Text = topic.Title;

            if (DataSource != null)
            {
                _messagesRepeater.DataSource = DataSource;
                _messagesRepeater.DataBind();
            }
            else
            {
                var posts = ForumRepository.GetForumPostsByTopicId(id);
                ForumRepository.IncreaseTopicViewCount(id);

                foreach (var post in posts)
                    post.TopicId = topic.Id;

                var page = 1;
                var pageSize = 15;
                int.TryParse(Request.QueryString["page"], out page);
                if (page < 1)
                    page = 1;

                var pageCount = (int)Math.Ceiling((double)posts.Count / pageSize);
                if (page > pageCount)
                    page = pageCount;

                if (Math.Max(1, page - 1) == 1)
                    pagerPrevLink.HRef = _topicLink.HRef;
                else
                    pagerPrevLink.HRef = _topicLink.HRef + "&page=" + Math.Max(1, page - 1);
                //pagerBottomPrevLink.HRef = pagerPrevLink.HRef;
                pagerPrevContainer.Visible = (page > 1);
                

                if (Math.Min(pageCount, page + 1) == 1)
                    pagerNextLink.HRef = _topicLink.HRef;
                else
                    pagerNextLink.HRef = _topicLink.HRef + "&page=" + Math.Min(pageCount, page + 1);
                //pagerBottomNextLink.HRef = pagerNextLink.HRef;
                pagerNextContainer.Visible = (page < pageCount);


                var postsPage = new List<ForumPostDto>();
                for (var i = (page - 1) * pageSize; i < Math.Min((page) * pageSize, posts.Count); i++)
                {
                    postsPage.Add(posts[i]);
                }


                _messagesRepeater.DataSource = postsPage;
                _messagesRepeater.DataBind();
            }

            _newLink.HRef = string.Format(_newLink.HRef, forum.Id);
            _newBottomLink.HRef = _newLink.HRef;
            _replyLink.HRef = string.Format(_replyLink.HRef, topic.Id);
            _replyBottomLink.HRef = _replyLink.HRef;

            var master = Page.Master;
            if(master != null)
            {
                var typedMaster = master as MasterBaseWithDesignHack;
                if(typedMaster != null)
                {
                    var dto = new RssLinksDto();
                    dto.RssUrl = forum.FeedBurnerUrl;
                    if (string.IsNullOrEmpty(dto.RssUrl))
                        dto.RssUrl = _forumLink.HRef + "&rss=1";
                    dto.RssTitle = forum.Title;

                    typedMaster.SetRssLinks(dto);
                }
            }
        }     
        public string GetPostClass(ForumPostDto dto, string cssClass, string noMatch)
        {
            if (dto == null)
                return noMatch;

            var user = SPContext.Current.Web.CurrentUser;
            if (user == null)
                return noMatch;

            if (user.LoginName == dto.AuthorUserName)
                return cssClass;

            return noMatch;
        }
        public string GetFormattedBody(ForumPostDto post)
        {
            if (post == null)
                return string.Empty;

            var body = post.Body;
            if (string.IsNullOrEmpty(body))
                return string.Empty;

            //var pattern = @"\[quote?[\s+name=""(?<user>.*)""]\](?<body>.*)\[\/quote\]";
            //var pattern = @"(\[quote\s+name=&quot;(?<user>\w+)&quot;\]|\[quote\])(?<body>[^\]]+)\[\/quote\]";
            var pattern = @"(\[quote\s+name=&quot;(?<user>\w+)&quot;\]|\[quote\])";
            var matches = Regex.Matches(body, pattern,RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (matches.Count == 0)
                return body;

            foreach (Match match in matches)
            {
                var user = string.Empty;
                if (match.Groups["user"] != null)
                    user = match.Groups["user"].Value;

                //var matchBody = string.Empty;
                //if (match.Groups["body"] != null)
                //    matchBody = match.Groups["body"].Value;

                var replace = string.Empty;

                if(!string.IsNullOrEmpty(user))
                {
                    replace += "<strong class=\"blockquote\">" + user + " " + Resources.Forum.UserWroteLabel + "</strong>";
                }
                //if (!string.IsNullOrEmpty(matchBody))
                //{
                //    replace += "<blockquote>" + matchBody + "</blockquote>";
                //}
                body = body.Replace(match.ToString(),replace+"<blockquote>");
            }
            body = body.Replace("[/quote]", "</blockquote>");
            body = body.Replace("<blockquote></p>", "<blockquote>");
            body = body.Replace("<p></blockquote>", "</blockquote>");
            body = body.Replace("<p><strong class=\"blockquote\">", "<strong class=\"blockquote\">");
            body = body.Replace("</blockquote></p>", "</blockquote>");
            body = body.Replace("<p>&nbsp;</p>", "");
            return body;
        }

        private UserProfileRepository _profileRepository;
        public UserProfileRepository ProfileRepository
        {
            get
            {
                if (_profileRepository != null)
                    return _profileRepository;

                _profileRepository = new UserProfileRepository(SPContext.Current.Web);
                return _profileRepository;
            }
        }

        public string GetProfileImageUrl(int profileId)
        {
            var profile = ProfileRepository.GetUserProfileById(profileId);
            if (profile == null)
                return string.Empty;

            return profile.UserImage32x32Url;
        }
    }
}